<template>
  <div>
    <el-dialog
      :visible.sync="editUserVisibleState"
      title="修改用户"
      @open="getDataById"
      @close="$store.commit('roles/editUserVisibleState', false)"
    >
      <el-form :model="editUserData" ref="editRolesForm" :rules="roleFormRules">
        <el-form-item label="用户名称" prop="roleName"
          ><el-input v-model="editUserData.roleName"></el-input
        ></el-form-item>
        <el-form-item label="角色描述" prop="roleDesc"
          ><el-input v-model="editUserData.roleDesc"></el-input
        ></el-form-item>
      </el-form>
      <template slot="footer">
        <el-button @click="$store.commit('roles/editUserVisibleState', false)"
          >取消</el-button
        >
        <el-button type="primary" @click="editUser(editUserData.roleId)"
          >提交</el-button
        >
      </template>
    </el-dialog>
  </div>
</template>

<script>
export default {
  name: 'EditUserDialog',
  props: ['id'],
  data() {
    return {
      // 编辑用户表单验证规则
      roleFormRules: {
        roleName: [
          { required: true, message: '请输入用户名', trigger: 'blur' }
        ],
        roleDesc: [
          { required: true, message: '请输入用户描述', trigger: 'blur' }
        ]
      },
      // 当前编辑的用户数据
      editUserData: {}
    }
  },
  methods: {
    // 从父组件拿到点击的用户的id，获得当前用户的数据
    async getDataById() {
      const { data: res } = await this.$http.get('roles/' + this.id)
      if (res.meta.status !== 200) return this.$message.error('获取对话框失败!')
      this.editUserData = res.data
      this.$store.commit('roles/editUserVisibleState', true)
    },
    // 提交用户编辑后的数据
    editUser(id) {
      this.$refs.editRolesForm.validate(async (valid) => {
        if (!valid) return this.$message.error('请正确填写表单！')
        const { data: res } = await this.$http.put('roles/' + id, {
          roleName: this.editUserData.roleName,
          roleDesc: this.editUserData.roleDesc
        })
        if (res.meta.status !== 200) return this.$message.error('数据提交失败!')
        this.$message.success('数据提交成功!')
        this.$store.commit('roles/editUserVisibleState', false)
        this.$emit('updateList')
      })
    }
  },
  computed: {
    editUserVisibleState: {
      get() {
        return this.$store.state.roles.editUserVisible
      },
      set() {
        this.$store.commit('roles/editUserVisibleState', false)
      }
    }
  }
}
</script>

<style></style>
